package com.xiao.community.pay;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xiao.community.controller.OrderController;
import com.xiao.community.entity.OrderEntity;
import com.xiao.community.service.OrderService;
import org.elasticsearch.search.DocValueFormat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

@RestController
@RequestMapping("community")
public class PayController {
    // 应用ID,支付宝提供的APPID，上面截图中有提到
    public static String app_id = "2021000118616604";

    // 商户私钥，您的PKCS8格式RSA2私钥
    public static String merchant_private_key = "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCNgd/NSEC7xtgzvNz1F/g7Y5ToKwyhYNVOCnAP4FjS3/Ghh1rDuqGcNzdl9xCYCMZzd4Z0PiA1IA9EKDsFhAlojyqC9hNYnh9r92d3ry8A1vW59D3/inq21HZvTvxzMbIotUxLWBep8wW+TuuXGPLEs+b5JWdKFoWZ37XUGIkklbGbQHO1KBuGd+N/Jv+yvmt4rbGJz+fAcq8uv7z/5DGU5As9su/thIS39dClr5lFzI9GdRpAnsTy8zQPeLovZUbwZzcHc/3xHIdE0yi/qVO2IR1McEs649mt53m8nJOPUYY4ucN5xeKJmisIQTPb3Bp5D06Pxjo1nu3MB9kUvkiDAgMBAAECggEAZKAFEIoflifZGDll+leYKksu2UW7joo4RG2BsJh9MT8UKSQCNArj3x0YpMZio2oiDHvjPYfsCTsKABKHne19bz/XIBdyPGL8vx7IEcCeMP+q7xeyeqPzjU1aBt7o/9VH9lCttyom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iY5Ed+7usnPu2M8";
    // 支付宝公钥,查看地址：https://openhome.alipay.com/platform/appDaily.htm 对应APPID下的支付宝公钥。
    public static String alipay_public_key = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAl4x5UptPY6fvoH9bygtArOtatSp5JrKkZUzV0ZyO9npSMpOn0rMa4XOpYm0xCel2VM+6XZf0Dz7grJExDXsRz6QZ17jwBhOUKJ01jX4SDZMAkU2BQswyhv8ipZ4sYajMpPIrFNdFHbpzKcY978FRkTjuIw/5c+eKODoECjuf23bILqSbpBLSEO6b+rOYgj0lAoxZOzRWJzLqBv8CD2OeDqb0M5BcZxTANV1o5ho927IUKnsBY91coGyHE54Vl4XpCnTO0g0ze92ys+9H/PE9DcnmrkidjXJQ/tCq+QqSisLLW0pkGliITGodZJh1sLi6XkxO/Gf7WkGcESllahOBPQIDAQAB";

    // 服务器异步通知页面路径  需http://格式的完整路径，不能加?id=123这类自定义参数，必须外网可以正常访问.如果只是测试使用,那么设置成自己项目启动后可以访问到的一个路径,作为支付宝发送通知的路径(有什么用暂时没发现)
    public static String notify_url = "http://localhost:88/api/community/notifyUrl";

    // 页面跳转同步通知页面路径 需http://格式的完整路径，不能加?id=123这类自定义参数，必须外网可以正常访问.如果只是测试使用,那么设置成自己项目启动后可以访问到的一个路径.是支付正常完成后,会访问的路径.
    public static String return_url = "http://localhost:88/api/community/notifyUrl";
    // 签名方式，注意这里，如果步骤设置的是RSA则用RSA,如果按照扇面步骤做的话,选择RSA2
    public static String sign_type = "RSA2";
    // 字符编码格式
    public static String charset = "utf-8";
    // 支付宝网关
    public static String gatewayUrl = "https://openapi.alipaydev.com/gateway.do";

    @Autowired
    public OrderService orderService;

    @Autowired
    public OrderController orderController;

    @Transactional
    @RequestMapping("/alipay")
    public String alipay(HttpServletResponse httpResponse,
                         @RequestParam("orderId")String orderId
                       ) throws Exception {
        //实例化客户端,填入所需参数
        AlipayClient alipayClient = new DefaultAlipayClient(gatewayUrl, app_id, merchant_private_key, "json", charset, alipay_public_key, sign_type);
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        //在公共参数中设置回跳和通知地址
        request.setReturnUrl(return_url);
        request.setNotifyUrl(notify_url);

        OrderEntity orderid = orderService.getOne(new QueryWrapper<OrderEntity>().eq("order_id", orderId));
        System.out.println(orderid);

        //商户订单号，商户网站订单系统中唯一订单号，必填
//        生成随机Id
        String out_trade_no = orderid.getOrderId();
        //付款金额，必填
//        String total_amount = String.valueOf(orderid.getAllmoney());
//        String total_amount= orderid.getAllmoney();
        String total_amount = String.valueOf(orderid.getAllmoney());

        //订单名称，必填
        String subject =orderid.getGoodsName();
        //商品描述，可空
        String body = "";
        request.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
                + "\"total_amount\":\""+ total_amount +"\","
                + "\"subject\":\""+ subject +"\","
                + "\"body\":\""+ body +"\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        String form = "";
        try {
            form = alipayClient.pageExecute(request).getBody(); // 调用SDK生成表单
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        httpResponse.setContentType("text/html;charset=utf-8");
        httpResponse.getWriter().write(form);// 直接将完整的表单html输出到页面
        httpResponse.getWriter().flush();
        httpResponse.getWriter().close();
        return form;
    }

    @RequestMapping("/notifyUrl")
    @ResponseBody
    public String returnUrl(HttpServletRequest request, HttpServletResponse response)
            throws IOException, AlipayApiException {
        System.out.println("=================================同步回调=====================================");

        // 获取支付宝GET过来反馈信息
        Map<String, String> params = new HashMap<String, String>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            // 乱码解决，这段代码在出现乱码时使用
            valueStr = new String(valueStr.getBytes("utf-8"), "utf-8");
            params.put(name, valueStr);
        }

        System.out.println(params);//查看参数都有哪些
        boolean signVerified = AlipaySignature.rsaCheckV1(params, alipay_public_key, charset, sign_type); // 调用SDK验证签名
        //验证签名通过
        if(signVerified){
            // 商户订单号
            String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"), "UTF-8");

            // 支付宝交易号
            String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"), "UTF-8");

            // 付款金额
            String total_amount = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"), "UTF-8");

            System.out.println("商户订单号="+out_trade_no);
            System.out.println("支付宝交易号="+trade_no);
            System.out.println("付款金额="+total_amount);

            //支付成功，修复支付状态
            OrderEntity orderid = orderService.getOne(new QueryWrapper<OrderEntity>().eq("order_id", out_trade_no));
            orderid.setIfzhifu(1);
            orderid.setOrderZhifu(new Date());
            orderController.update(orderid);
            return "ok";//跳转付款成功页面
        }else{
            return "no";//跳转付款失败页面
        }

    }
}
